package org.stratusdb.logging;

import java.rmi.server.ServerNotActiveException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import org.stratusdb.Config;

public class DatabaseHandler extends Handler {

	private Connection conn = null;
	
	/**
	 * Constructs a new DatabaseHandler.
	 * 
	 * @throws ServerNotActiveException
	 */
	public DatabaseHandler() throws ServerNotActiveException {
		// get connection
		try
		{
			Class.forName(Config.METADATA_DRIVER_CLASS);
			conn = DriverManager.getConnection(
				Config.METADATA_DATABASE_URL, Config.METADATA_USER,Config.METADATA_PASSWORD);
		} catch(Exception e)
		{
			throw new ServerNotActiveException(e.getMessage());
		}

		try
		{
			Statement create = conn.createStatement();
			create.execute("CREATE TABLE \""+Config.METADATA_SCHEMA+"\".\"LOG\" ("+
							   "log_id serial NOT NULL,"+ 
							   "log_time timestamp without time zone NOT NULL,"+ 
							   "log_level integer NOT NULL,"+ 
							   "log_message text NOT NULL,"+ 
							   "log_sourceClass text NOT NULL,"+
							   "log_sourceMethod text NOT NULL,"+ 
							   "CONSTRAINT pk_log_id PRIMARY KEY (log_id))");
		}
		catch(Exception e)
		{
			// Table Log already existed. So we can log now.
		}
	}

	/**
	 * Closes the connection.
	 */
	@Override
	public void close() throws SecurityException {
		try {
			conn.close();
		} catch (SQLException e) {
			throw new SecurityException(e.getMessage());
		}
	}

	/**
	 * This method does nothing, because this Handler flushes its contents immediately.
	 */
	@Override
	public void flush() {
		return;

	}

	@Override
	public void publish(LogRecord record) {
		try {
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("INSERT INTO \""+Config.METADATA_SCHEMA+"\".\"LOG\"(log_time,log_level,log_message,log_sourceClass,log_sourceMethod) VALUES("+
				"to_timestamp("+(record.getMillis()/1000.0)+"),"+record.getLevel().intValue()+",'"+
					record.getMessage()+"','"+record.getSourceClassName()+"','"+
					record.getSourceMethodName()+
				"')"
			);
		} catch (SQLException e) {
			System.out.println("We could not log: "+e.getMessage());
		}
	}

}
